import BottomView from '@/components/BottomView/index';
import CarbonBedEffectView from '@/components/CarbonBedEffectView'; // 假设这是“碳床效果”对应的组件
import ChaiHuoSoundView from '@/components/ChaiHuoSoundView';
import FlameEffectView from '@/components/FlameEffectView'; // 假设这是“火焰”对应的组件
import LutangFenweiView from '@/components/LutangFenweiView';
import MainPageView from '@/components/MainPageView';
import MenuView from '@/components/MenuView';
import RanShaoMuCHai from '@/components/RanShaoMuCHai';
import RoomFenWei from '@/components/RoomFenWei';
import { getStatusBarHeight, rpx2pxNum } from '@/utils';
import { View, device, exitMiniProgram, getDpsInfos, hideMenuButton, router } from '@ray-js/ray';
import { Dialog, DialogInstance, Icon, NavBar } from '@ray-js/smart-ui'; // 导入 SmartUI 提供的导航栏和按钮组件
import React, { createContext, useCallback, useState } from 'react';
import iconArrow from '../../res/imgs/ic_back_white.png';
import iconRight from '../../res/imgs/ic_setting.png';
import Styles from './index.module.less'; // 引入模块化样式
// Ray调用方式
import BottomDownTimerDialog from '@/components/BottomDownTimerDialog/BottomDownTimerDialog';
import BottomTureDialog from '@/components/BottomTureDialog/BottomTureDialog';
import { useActions } from '@ray-js/panel-sdk';
import { getLaunchOptionsSync, openDeviceDetailPage } from '@ray-js/ray';

// 导入ahooks中的工具函数
import MainDowTimerView from '@/components/MainDowTimerView';
import { useThrottleFn } from 'ahooks';

// 定义在组件外部，作为模块级常量 ✅ 推荐做法
export const HomeBottonContext = createContext<{
  onClickTimer: () => void;
}>({
  onClickTimer: () => { },
});

export function Home() {
  const barH = getStatusBarHeight(); // 状态栏 
  const top = barH + rpx2pxNum(88) + 10; // 状态栏 + 标题栏高度
  console.log('顶部高度', top);

  const { onDpDataChange } = device;
  // useEffect(() => {
  //   onDpDataChange((data) => {
  //     console.log('设备数据变更onDpDataChange:', data);//它只会变更只改变的状态值
  //   })
  // }, []);

  // 启动参数中获取设备 id
  const {
    query: { deviceId
    }
  } = getLaunchOptionsSync();
  console.log('设备ID:', deviceId); // 打印设备ID
  hideMenuButton();

  // 定义当前显示的组件
  const [currentComponent, setCurrentComponent] = useState(1);
  const actions = useActions();

  getDpsInfos({
    devId: deviceId,
    gwId: deviceId,
  })
    .then(res => {
      console.log('功能点成功：',res);
    })
    .catch(error => {
      console.log('功能点失败：',error);
    });

  // 处理按钮点击事件
  const handleButtonClick = (id: number) => {
    console.log('处理最终的点击事件', id);

    if (id == 8) {//火焰周定时
      // router.push("/flame")
      handleJump("flame")
    } else if (id == 9) {//取暖周定时
      // router.push("/heat")
      handleJump("heat")
    } else if (id == 10) {//温度单位
      setShowMenuDialog(true);
    } else {
      setCurrentComponent(id); // 显示火焰效果组件
    }
  };

  // 跳转页面的防抖函数
  const handleJump = useThrottleFn(
    (code: string) => {
      router.push(`/${code}`); // 跳转到指定页面
    },
    { wait: 80 }
  ).run;

  const [showMenuDialog, setShowMenuDialog] = React.useState(false);

  const [showTimeDialog, setShowTimeDialog] = React.useState(false);

  const onClickTimer = () => {//点击界面下面的定时按钮
    console.log('点击界面下面的定时按钮');
    // setHeating(value == 1);
    setShowTimeDialog(true);
  };

  const clickBottomTimerDialog = useCallback((value: number) => {
    setShowTimeDialog(false)
    //点击了倒计时弹窗外部区域
    console.log('收到倒计时弹窗的逻辑', value);
    if (value == 0) {
      openTimeZeroDialog()
    }
    if (value > 0 && value < 1440) {
      actions.DownTimer_Set.set(value);
    }

  }, [])

  //点击左边返回按钮
  const clikBack = () => {
    console.log('点击了返回按钮')

    if (currentComponent == 1) {
      exitMiniProgram()
    } else {
      setCurrentComponent(1);
    }
  };

  //点击右侧进入设备详情页
  const clickSettings = () => {
    openDeviceDetailPage({
      deviceId,
      success: () => {
        console.log('openDeviceDetailPage success');
      },
      fail: (error) => {
        console.log('openDeviceDetailPage fail', error);
      }
    });
  };

  const openTimeZeroDialog = () => {
    DialogInstance.confirm({
      selector: '#dialog',
      title: '提示',
      message: '倒计时时间要大于1分钟',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      customStyle: { backgroundColor: '#353535', color: '#353535' },
    })
      .then(() => {
        // 确认
      })
      .catch(() => {
        // 取消
      });
  };

  return (
    <View className={Styles.app}>
      <View className={Styles.view}>
        <NavBar
          customClass={Styles.titlebar}
          leftArrow={false}
          safeAreaInsetTop={true} //是否留出安全距离
          title='Home'
          fixed={true}
          slot={{
            left: (
              <View style={{ width: '40px', height: '40px', display: 'flex', flexDirection: 'row', justifyContent: 'flex-start' }} onClick={clikBack}>
                <Icon name={iconArrow} size="20px" />
              </View>
            ),
            right: (
              <View style={{ width: '40px', height: '40px', display: 'flex', flexDirection: 'row', justifyContent: 'flex-end' }} onClick={clickSettings}>
                <Icon name={iconRight} size="25px" />
              </View>
            )
          }}
        />
        {/* //需要穿透点击事件 */}
        <View style={{ display: 'flex', flexDirection: 'column', width: 'auto', height: 'auto', position: 'absolute', zIndex: 100, marginTop: `${top}px` }}>
          <MenuView onButtonClick={handleButtonClick} index={currentComponent} /> {/* 传递回调函数 */}
        </View>
        <View onClick={() => {onClickTimer()  }} style={{ paddingTop: '20rpx', display: 'flex', flexDirection: 'row', width: 'auto', height: 'auto', position: 'absolute', right: '30rpx', zIndex: 100, top: `${top}px` }}>
          <MainDowTimerView />
        </View>

        <View className={Styles.min} style={{ paddingTop: `${barH}px` }}>
          <View className={Styles.circle}>
            {currentComponent == 1 && <MainPageView />}
            {currentComponent == 2 && <FlameEffectView />}
            {currentComponent == 3 && <ChaiHuoSoundView />}
            {currentComponent == 4 && <CarbonBedEffectView />}
            {currentComponent == 5 && <RanShaoMuCHai />}
            {currentComponent == 6 && <LutangFenweiView />}
            {currentComponent == 7 && <RoomFenWei />}
          </View>
            <BottomView />
        </View>
      </View>
      <Dialog
        id="dialog"
        title='提示'
        message='倒计时时间要大于1分钟'
        customClass={Styles.dialog}
      />
      {showMenuDialog && <View style={{ display: 'flex', position: 'absolute', width: '100%', height: '100%', zIndex: 200 }}>
        <BottomTureDialog onClick={() => {
          setShowMenuDialog(false)
        }} />
      </View>}
      {showTimeDialog && <View style={{ display: 'flex', position: 'absolute', width: '100%', height: '100%', zIndex: 200 }}>
        <BottomDownTimerDialog onClick={clickBottomTimerDialog} />
      </View>}

    </View>
  );
}


export default Home;